﻿using DataWorks_Tools.BasicMethods;
using DataWorks_Tools.CleanDetails;
using DataWorks_Tools.MappModals;
using Microsoft.VisualBasic;
//using NetAutoGUI;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace DataWorks_Tools.ConverttoCSVI
{
    public static class ConvertoCSVIDetails
    {
        private static readonly double interval = 0.001953125;
        public static async Task<List<string>> YXHExcuteConverttoCSVIAsync(CSVIModalforProcess row)
        {
            List<string> list = new List<string>
            {
                "CSVI转换程序执行完成"
            };
            var dirs = BasicFilesOperation.YXHGetProcessedDateDir(row.odpath, row.datedir);
            if (dirs != null)
            {
                Stopwatch Btimer = new Stopwatch();
                Btimer.Start();
                foreach (var d in dirs)
                {
                    Stopwatch Stimer = new Stopwatch();
                    Stimer.Start();
                    //先定义输出日期目录文件夹路径
                    string resultdirectorypath = Path.Combine(row.rdpath, d.Name);
                    DirectoryInfo root = new DirectoryInfo(resultdirectorypath);
                    //创建日期目录文件夹
                    if (!root.Exists)
                    {
                        root.Create();
                    }
                    var csvs = d.FullName.YXHGetAllextFiles("*.csv");
                    if (csvs.Length > 0)
                    {
                        foreach(var csv in csvs)
                        {
                            var filenamedate = csv.YXHFilenametoDateTime();
                            var lst=await File.ReadAllLinesAsync(csv.FullName);
                            //首行标题行不用动，从第二行开始
                            for (int i = 0; i < lst.Length; i++)
                            {
                                //把每行标题行间隔符改为分号
                                var t = lst[i].Replace(",", ";");
                                if (i == 0)
                                {
                                    lst[0] = t;
                                }
                                else
                                {
                                    //间隔符改为分号
                                    int index = t.IndexOf(';'); // 获取第一个分号的索引位置
                                    if (index != -1)
                                    {
                                        // 将第一个分号前面的部分替换为时间
                                        lst[i] = filenamedate.AddSeconds((i - 1) * interval).ToString("yyyy/MM/dd HH:mm:ss.fffffff") + t.Substring(index);
                                    }
                                }
                            }
                            var csviresultpath = Path.Combine(resultdirectorypath, csv.Name+"i");
                            await File.WriteAllLinesAsync(csviresultpath, lst);
                        }
                    }
                    else
                    {
                        list.Add($"{row.odpath}路径下没有csv文件");
                    }
                    Stimer.Stop();
                    list.Add($"{d.Name}转换完成时间为{Stimer.Elapsed.TotalMinutes:0.00}分");

                }
                Btimer.Stop();
                list.Add($"转换程序总完成时间为{Btimer.Elapsed.TotalMinutes:0.00}分-单线程");

            }

            return list;
        }

        public static async Task<List<string>> YXHExcuteConverttoCSVIMultiThreadsAsync(CSVIModalforProcess row)
        {
            List<string> list = new List<string>
            {
                "CSVI转换程序执行完成"
            };
            var dirs = BasicFilesOperation.YXHGetProcessedDateDir(row.odpath, row.datedir);
            if (dirs != null)
            {
                Stopwatch Btimer = new Stopwatch();
                Btimer.Start();
                foreach (var d in dirs)
                {
                    Stopwatch Stimer = new Stopwatch();
                    Stimer.Start();
                    //先定义输出日期目录文件夹路径
                    string resultdirectorypath = Path.Combine(row.rdpath, d.Name);
                    DirectoryInfo root = new DirectoryInfo(resultdirectorypath);
                    //创建日期目录文件夹
                    if (!root.Exists)
                    {
                        root.Create();
                    }
                    var csvs = d.FullName.YXHGetAllextFiles("*.csv");
                    if (csvs.Length > 0)
                    {
                        //文件数据集被划分成了多个子集，子集数目按照线程数量来
                        var dividedData = csvs.DivideDataIntoParts(row.csvithread);
                        List<Task> tasks = new List<Task>();
                        foreach (var part in dividedData)
                        {
                            Task task = Task.Run(async () =>
                            {
                                foreach (var csv in part)
                                {
                                    var filenamedate = csv.YXHFilenametoDateTime();
                                    var lst = await File.ReadAllLinesAsync(csv.FullName);
                                    //首行标题行不用动，从第二行开始
                                    for (int i = 0; i < lst.Length; i++)
                                    {
                                        //把每行标题行间隔符改为分号
                                        var t = lst[i].Replace(",", ";");
                                        if (i == 0)
                                        {
                                            lst[0] = "Time;"+t;
                                        }
                                        else
                                        {
                                            t = "0;" + t;
                                            //间隔符改为分号
                                            int index = t.IndexOf(';'); // 获取第一个分号的索引位置
                                            if (index != -1)
                                            {
                                                var s = (i - 1) * interval;
                                                // 将毫秒转换为TimeSpan对象
                                                TimeSpan timeSpan = TimeSpan.FromMilliseconds(s*1000);

                                                // 计算新的时间
                                                DateTime newDate = filenamedate.Add(timeSpan);
                                                // 将第一个分号前面的部分替换为时间
                                                lst[i] = newDate.ToString("yyyy/MM/dd HH:mm:ss.ffffff") + t.Substring(index);
                                            }
                                        }
                                    }
                                    var csviresultpath = Path.Combine(resultdirectorypath, csv.Name + "i");
                                    await File.WriteAllLinesAsync(csviresultpath, lst);
                                }
                            });
                            tasks.Add(task);
                        }
                        await Task.WhenAll(tasks.ToArray());
                    }
                    else
                    {
                        list.Add($"{row.odpath}路径下没有csv文件");
                    }
                    Stimer.Stop();
                    list.Add($"{d.Name}转换完成时间为{Stimer.Elapsed.TotalMinutes:0.00}分");

                }
                Btimer.Stop();
                list.Add($"转换程序总完成时间为{Btimer.Elapsed.TotalMinutes:0.00}分-多线程");

            }

            return list;
        }
    }
}
